#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import json
import logging
import datetime
import traceback

from Ump import utils, defs
from Ump.common.remote import _put_remote, _get_remote, _get_remote_file, _exec_remote,\
                ssh_key, _check_authentication, _dir_put_remote, _dir_get_remote, _check_remote_file_exists

from Ump.common import config, oem_conf, log, http


from Ump.lich.base import LichBase
from Ump.objs.task.manager import TaskManager

from Ump.websocket import send

#LOG = logging.getLogger('Ump.objs.manage')
LOG = log.init_info_logger()


class Manager(object):
    '''
    '''
    MODEL = None

    def __init__(self):

        self.cluster_id = None
        self.taskm = TaskManager()

        # delegate

        self.lich = LichBase()

        self.install_path = utils.install_path
        self.ump_home = utils.ump_home
        self.utils = utils
        self.defs = defs
        self.is_fusionnas = defs.PRODUCT_NAME == 'fusionnas'

        self._ssh_key = ssh_key
        self._exec_remote = _exec_remote
        self._get_remote_file =  _get_remote_file
        self._check_files = _check_remote_file_exists
        self._check_authentication = _check_authentication
        self._dir_put_remote = _dir_put_remote
        self._dir_get_remote = _dir_get_remote
        self.put_remote = _put_remote
        self.get_remote = _get_remote
        self._http_down = http.http_down
        self.http_download = http.http_download
        self.get_remote_file = _get_remote_file
        self._exec_pipe = utils._exec_pipe
        self.lich_home = config.lich_home
        self.check_network = utils.check_network
        self.send_message = send.send_message
        self.storagent_port = config.storagent_port

    def __getattr__(self, item):
        return getattr(self.lich, item)

    def _deploy_agent(self, ip, passwd, lich_home=config.lich_home):
        #managerServerIP = utils._system_ip() 
        #if not managerServerIP :
        #    raise Exception(u'controller node have no available IP')


        agent_dir = utils.storagent_path
        agent_remote_dir = os.path.join(self.lich_home, 'storagent')
        self._dir_put_remote(ip, agent_dir, agent_remote_dir, password=passwd, ischmod=True)

        self._install_agent(ip, passwd, lich_home)
        self._restart_agent(ip, passwd, lich_home)

    def _install_agent(self, ip, passwd, lich_home):
        install_agent_cmd = 'bash %s/storagent/install.sh' % self.lich_home
        res = self._exec_remote(ip, install_agent_cmd, password=passwd, iscode=True)

    def _restart_agent(self, ip, passwd, lich_home=config.lich_home):
        adaemon_path = 'bash %s/storagent/storagent/storagent_server.sh' % self.lich_home
        agent_restart_cmd = '%s stop; %s start' % (adaemon_path, adaemon_path)
        res = self._exec_remote(ip, agent_restart_cmd, password=passwd, iscode=True)

    @property
    def get_extra(self):
        '''得到一个extra，在记录日志时的参数'''
        if self.cluster_id is None:
            return {}
        return {'cluster_id': self.cluster_id}

    def ump_sync(self,cluster_id):
        lfile = '/dev/shm/ump_lock'
        if os.path.exists(lfile):
            os.system('rm -rf %s'%(lfile))
        utils._exec_pipe('ump-sync -p %s'%cluster_id)

    def is_product_alert(self, returncode):
        alert = self.db_api.alert_get_with_returncode(returncode)
        delta = datetime.timedelta(seconds=20)
        now = datetime.datetime.now()
        return not alert or (alert and now - alert.created_at > delta)


    def api_async_call(self, cmd, uuid, path, host_ip, cluster_id=None, timeout=300):
        if cluster_id:
            host_ip, hostname = self._select_host(cluster_id, is_hostname=True)

        if host_ip:
            utils._exec_http_async(cmd, uuid, host_ip, config.storagent_port, path, timeout)
        else:
            # LOG.error("%s no target host" % (msg.get('cmd')))
            raise Exception(u"未指定目标节点")


if __name__ == '__main__':
    a = Manager()
    a._deploy_agent('192.168.120.72','mdsmds123')
